#!/usr/bin/env python

import RPi.GPIO as GPIO
import commands, time, threading, signal

gpin = 40
gstfan = False

def get_cpu_temp():
    tempFile = open( "/sys/class/thermal/thermal_zone0/temp" )
    cpu_temp = tempFile.read()
    tempFile.close()
    return float(cpu_temp)/1000
 
def get_gpu_temp():
    gpu_temp = commands.getoutput( '/opt/vc/bin/vcgencmd measure_temp' ).replace( 'temp=', '' ).replace( '\'C', '' )
    return  float(gpu_temp)

def create_timer(interval=1.0):
    global gtimer
    gtimer = threading.Timer(interval, check_temp)
    return gtimer

def check_temp():
    global gstfan
    try:
        if gstfan == True:
            threshold = 40
        else:
            threshold = 50
        cputmp, gputmp, stfan = get_cpu_temp(), get_gpu_temp(), False
        if cputmp > threshold:
            stfan = True
        if gputmp > threshold:
            stfan = True
        if gstfan != stfan:
            gstfan = stfan
            if stfan == True:
                GPIO.output(gpin, GPIO.HIGH)
            else:
                GPIO.output(gpin, GPIO.LOW)
            print("%s cpu temp is %f, gpu temp is %f, threshold is %f")%(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), cputmp, gputmp, threshold)
    except BaseException as e:
        print('except:', e)
    finally:
        if gstfan == True:
            create_timer(15.0).start()
        else:
            create_timer().start()

def exit():
    print("GPIO cleanup")
    GPIO.cleanup()

def main():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(gpin, GPIO.OUT, initial=GPIO.LOW)
    create_timer().start()
    signal.signal(signal.SIGINT, exit)
    signal.signal(signal.SIGTERM, exit)

if __name__ == '__main__':
    main()